<template>
  <el-dialog
    v-loading="isLoading"
    :before-close="handleClose"
    :visible.sync="dialogVisible"
    title="选择头像"
    width="800px">
    <div class="detail-cropper">
      <vue-cropper
        ref="vueCropper"
        :img="base64"
        :auto-crop-width="178"
        :auto-crop-height="178"
        :info="false"
        fixed-box
        auto-crop
        output-type="png"
        class="detail-cropper-item" />
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="headImgSave()">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { VueCropper } from 'vue-cropper'
export default {
  components: {
    VueCropper
  },
  props: {
    img: {
      type: File,
      required: true
    }
  },
  data() {
    return {
      dialogVisible: false,
      isLoading: false,
      base64: null
    }
  },
  methods: {
    handleClose() {
    },
    toggle(type) {
      this.isLoading = true
      if (type) {
        if (!this.img) return
        this.readImg(this.img).then(base64 => {
          this.base64 = base64
          this.dialogVisible = type
          this.isLoading = false
        })
      }
    },
    readImg(img) {
      return new Promise(resolve => {
        const reader = new FileReader()
        reader.readAsDataURL(img)
        reader.onload = (event) => {
          resolve(event.target.result)
        }
      })
    },
    headImgSave() {
      this.isLoading = true
      this.$refs.vueCropper.getCropData(data => {
        this.$emit('img-cropper', data)
        this.isLoading = false
        this.dialogVisible = false
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.detail-cropper{
  .detail-cropper-item{
    height: 400px;
  }
}
</style>
